<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Index extends CI_Controller {
    private function user_info(){
        define("WEIXIN_APPID", HAO_WEIXIN_APPID);
        define("WEIXIN_APPSECRET", HAO_WEIXIN_APPSECRET);
        define("WEIXIN_MCHID", HAO_WEIXIN_MCHID);
        define("WEIXIN_KEY", HAO_WEIXIN_KEY);
        $this->load->library('session');
        $this->load->library('WxPayPubHelper/SDKRuntimeException.php');
        $this->load->library('WxPayPubHelper/WxPaypubconfig.php');
        $this->load->library('WxPayPubHelper/WxPayPubHelper.php');
        //使用jsapi接口
        $jsApi = new \JsApi_pub();

        $user_info = $this->session->userdata('user_info');
        if(empty($user_info)){
            //通过code获得openid
            define("JS_API_CALL_URL", HAO_REDICT_URL);
            //微信登录返回code
            $code = $this->input->get('code');
            if (!$code) {
                //触发微信返回code码
                $url = $jsApi->createOauthUrlForCode(JS_API_CALL_URL);
                Header("Location: $url");
            } else {
                $jsApi->setCode($code);
                $openid = $jsApi->getOpenId();
                if($openid == false){
                    exit(" 请求失败 未获取 openid,");
                }
            }
            $user_info = $jsApi->user_info($openid);
            if( isset($user_info['errcode']) ){
                var_dump($user_info);die;
            }
            $this->session->set_userdata('user_info',$user_info);
        }
        return $user_info;
    }
	public function login()
	{
        $user_info = $this->user_info();
        $open_id = $user_info["openid"];;
        $nickname = $user_info["nickname"];;
        var_dump($open_id);
        var_dump($nickname);
        $Referer = $this->session->userdata('Referer');
        if(empty($Referer)){
            $Referer = "/";
        }
        Header("Location: $Referer");

	}

    public function image(){
        if($this->input->get('src')){
            t_(file_get_contents($this->input->get('src')));
        }
        $this->output->cache(60*24*7);
    }
    public function watch(){
        $this->load->library('simple_html_dom.php');
// 新建一个Dom实例
        $html = new simple_html_dom();
        $url = "https://mp.weixin.qq.com/s?__biz=MzA4NzkxNTc4Mg==&mid=2650771541&idx=1&sn=2f7f144fee1d16575286101b366c4d4a&scene=0#wechat_redirect";
// 从url中加载
        $html->load_file($url);
        $page_content = $html->find('html',0);
        foreach($page_content->find("img") as &$img){
            $img->src = "/i?src=".$img->getAttribute("data-src");
        }
        t_($page_content->outertext);
        $this->ad_logic();
        $this->output->cache(60*24*7);
    }


    public function ad_logic(){
        $this->load->view('ad/ad_logic');
        $this->load->view('ad/ad_logic_1');
        $this->load->view('ad/ad_logic_2');
        $this->load->view('ad/ad_logic_3');
        $this->load->view('ad/ad_logic_4');
    }
}
